<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入昵称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="标签" prop="label">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入标签"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="是否可用" prop="isEnable">
        <el-select v-model="queryParams.isEnable" placeholder="是否可用" clearable size="small">
          <el-option
            v-for="dict in enableOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>

      </el-form-item>

      <el-form-item label="会员身份" prop="memPerm">
        <el-select v-model="queryParams.memPerm" placeholder="会员身份" clearable size="small">
          <el-option
            v-for="dict in memPermOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>

      </el-form-item>

      <el-form-item label="关注状态" prop="memPerm">
        <el-select v-model="queryParams.isWxsub" placeholder="关注状态" clearable size="small">
          <el-option
            v-for="dict in isWxSubOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>

      </el-form-item>

      <el-form-item label="注册时间">
        <el-date-picker
          v-model="dateRange"
          :unlink-panels="unlinkPanels"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-chat-dot-round"
          size="mini"
          @click="handleWxMsg"
          v-hasPermi="['member:member:msgSend']"
        >微信通知</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-message"
          size="mini"
          @click="handleSmsMsg"
          v-hasPermi="['member:member:msgSend']"
        >短信通知</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-chat-dot-round"
          size="mini"
          @click="handleWxMsgSelected"
          v-hasPermi="['member:member:msgSend']"
        >[勾选]微信通知</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-message"
          size="mini"
          @click="handleSmsMsgSelected"
          v-hasPermi="['member:member:msgSend']"
        >[勾选]短信通知</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="头像" align="center" prop="avator" >-->
<!--        <template slot-scope="scope">-->
<!--          <el-avatar shape="square" :size="60"  :src="ossPreview+ scope.row.avator"></el-avatar>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="昵称" align="center" prop="nickName" />-->
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="身份" align="center" prop="memPerm" :formatter="memPermFormat"/>
      <el-table-column label="状态" align="center" prop="isEnable" :formatter="enableFormat"/>
      <el-table-column label="关注状态" align="center" prop="isWxsub" :formatter="isWxsubFormat"/>
      <el-table-column label="标签" align="center" prop="label" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="推荐人" align="center" prop="parentMobile" />
      <el-table-column label="归属地" align="center" prop="mobileloc" />
      <el-table-column label="注册时间" align="center" prop="gmtTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-dropdown trigger="click">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown" >
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['member:member:edit']"
                >修改
                </el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-postcard"
                  @click="handleCoupon(scope.row)"
                  v-hasPermi="['member:coupon:list']"
                >优惠券</el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-bicycle"
                  @click="handleCar(scope.row)"
                  v-hasPermi="['member:car:list']"
                >车辆</el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-s-order"
                  @click="handleOrder(scope.row)"
                  v-hasPermi="['order:order:list']"
                >订单</el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-user-solid"
                  @click="handleTg(scope.row)"
                  v-hasPermi="['member:member:list']"
                >推广下级</el-button>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--会员信息修改对话框-->
    <el-dialog :title="title" :visible.sync="editopen" :destroy-on-close="destroy" width="800px">

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入司机姓名" disabled/>
        </el-form-item>
        <el-form-item label="标签" prop="label">
          <el-input v-model="form.label" placeholder="请输入标签"/>
        </el-form-item>

        <el-form-item label="是否可用" prop="isEnable">
          <el-select v-model="form.isEnable" placeholder="请输入是否可用" clearable size="small">
            <el-option
              v-for="dict in enableOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="会员身份" prop="orderSwitch">
          <el-select v-model="form.memPerm" placeholder="请选择会员身份" clearable >
            <el-option
              v-for="dict in memPermOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="备注"/>
        </el-form-item>
        <el-form-item label="销售员提成" prop="salerProfit">
          <el-input-number v-model="form.salerProfit" placeholder="销售员订单提成"  :step="1" :min="-1"
                           :max="20"/><span style="color: red">*销售员订单提成，-1代表使用系统默认配置</span>
        </el-form-item>
        <el-form-item label="超级VIP提成" prop="superVipProfit">
          <el-input-number v-model="form.superVipProfit" placeholder="超级VIP订单提成"  :step="1" :min="0"
                           :max="100"/><span style="color: red">*实际提成 = 设置提成 - 订单优惠券金额</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="editcancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1100px" v-dialogdrag>
     <member-coupon :memberId="memberId" :key="(new Date().getTime())"></member-coupon>
    </el-dialog>

    <!-- 车辆对话框 -->
    <el-dialog :title="title" :visible.sync="carOpen" width="1300px" v-dialogdrag>
     <member-car :memberId="memberId" :key="(new Date().getTime())"></member-car>
    </el-dialog>

    <!-- 订单对话框 -->
    <el-dialog :title="title" :visible.sync="orderOpen" width="1400px" v-dialogdrag>
      <order-list :memberId="memberId" :key="(new Date().getTime())"></order-list>
    </el-dialog>

    <!-- 我的推广对话框 -->
    <el-dialog :title="title" :visible.sync="tgOpen" width="1400px" v-dialogdrag>
      <tg-member :parentId="parentId" :key="(new Date().getTime())"></tg-member>
    </el-dialog>

    <!--微信模板消息编辑对话框-->
    <el-dialog :title="wxtitle" :visible.sync="wxopen" :destroy-on-close="destroy" width="800px">

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="mobile">
          <el-input v-model="wxMsg.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" prop="label">
          <el-input v-model="wxMsg.content" placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item label="链接" prop="remark">
          <el-input v-model="wxMsg.path" placeholder="链接地址"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="wxsubmitForm">确 定</el-button>
        <el-button @click="wxeditcancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--短信模板消息编辑对话框-->
    <el-dialog :title="smstitle" :visible.sync="smsopen" :destroy-on-close="destroy" width="800px">

      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="通知内容" prop="orderSwitch">
          <el-select v-model="smsMsgTemp" placeholder="请选择通知类型" clearable >
            <el-option
              v-for="dict in msgSendTempOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="smssubmitForm">确 定</el-button>
        <el-button @click="smseditcancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入会员车辆对话框 -->
    <el-dialog title="导入会员车辆" :visible.sync="importMemberOpen" v-if= "importMemberOpen" width="500px">
      <el-upload
        class="upload-demo"
        drag
        :action="action"
        :headers="headers"
        :limit = "limit"
        :on-success="handleUploadSuccess"
        :before-upload="beforeUpload"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="importMemberOpen = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMember, getMember, delMember, addMember, updateMember, msgSend,msgSendBySelected } from "@/api/member/member";
import defaultSettings from '@/settings'
import memberCoupon from './MemberCoupon'
import memberCar from './MemberCar'
import tgMember from './TgMember'
import orderList from '../../order/order/index'
import {mapGetters} from "vuex";
export default {
  name: "Member",
  components:{memberCoupon,memberCar,orderList,tgMember},
  computed: {
    ...mapGetters(['token']),
    headers() {
      return{
        "Authorization": this.token // 直接从本地获取token就行
      }
    }
  },
  data() {
    return {
      memberId:null,
      parentId:null,
      ossPreview: defaultSettings.ossPreview,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      memberList: [],
      // 弹出层标题
      title: "",
      destroy: true,
      // 是否显示弹出层
      open: false,
      editopen: false,
      wxopen: false,
      smsopen: false,
      carOpen: false,
      orderOpen: false,
      tgOpen: false,
      importMemberOpen: false,
      wxtitle: '',
      smstitle: '',
      // 查询参数
      dateRange: [],
      unlinkPanels:true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mobile: undefined,
        nickName: undefined,
        avator: undefined,
        openId: undefined,
        password: undefined,
        parentId: undefined,
        gmtTime: undefined,
        memPerm: undefined,
        isEnable: undefined,
        label: undefined,
        isWxsub: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      enableOptions: [],
      memPermOptions: [],
      isWxSubOptions: [],
      msgSendTempOptions: [],
      sendType: null,
      smsMsgTemp: null,
      sendBySelected: false,
      wxMsg: {
        title: '',
        content: '',
        path: ''
      },
      action: process.env.VUE_APP_BASE_API + '/member/member/importMember',
      limit: 1
    };
  },
  created() {
    this.getList();

    this.getDicts("sys_is_enable").then(response => {
      this.enableOptions = response.data;
    });

    this.getDicts("mem_perm").then(response => {
      this.memPermOptions = response.data;
    });

    this.getDicts("is_wxsub").then(response => {
      this.isWxSubOptions = response.data;
    });
    this.getDicts("msg_send_temp").then(response => {
      this.msgSendTempOptions = response.data;
    });
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listMember(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.memberList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 取消按钮
    editcancel() {
      this.editopen = false;
      this.reset();
    },
    // 取消按钮
    wxeditcancel() {
      this.wxopen = false;
      this.reset();
    },
    // 取消按钮
    smseditcancel() {
      this.smsopen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        mobile: undefined,
        nickName: undefined,
        avator: undefined,
        openId: undefined,
        password: undefined,
        parentId: undefined,
        gmtTime: undefined,
        unionid: undefined,
        memPerm: undefined,
        isEnable: undefined,
        label: undefined,
        remark: undefined,
        salerProfit: -1,
        superVipProfit: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMember(id).then(response => {
        this.form = response.data;
        this.editopen = true;
        this.title = "修改会员信息";
      });
    },
    /** 修改按钮操作 */
    handleCoupon(row) {
      this.reset();
      const id = row.id || this.ids
      this.memberId = row.id;
      getMember(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "会员代金券";
      });
    },
    /** 修改按钮操作 */
    handleCar(row) {
      this.memberId = row.id;
      this.carOpen = true;
      this.title = "会员车辆";
    },
    /** 修改按钮操作 */
    handleOrder(row) {
      this.memberId = row.id;
      this.orderOpen = true;
      this.title = "会员订单";
    },

    /** 修改按钮操作 */
    handleTg(row) {
      this.parentId = row.id;
      this.tgOpen = true;
      this.title = "我的推广";
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateMember(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.editopen = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addMember(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.editopen = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    wxsubmitForm: function() {
      let params = {
        query: this.queryParams,
        type: this.sendType,
        wxMsg: this.wxMsg,
        ids:   this.ids,
      }
      if (this.sendBySelected){
        msgSendBySelected(params).then(response => {
          if (response.code === 200) {
            this.msgSuccess("操作成功");
            this.wxopen = false;
          } else {
            this.msgError(response.msg);
          }
        });
      }else{
        msgSend(params).then(response => {
          if (response.code === 200) {
            this.msgSuccess("操作成功");
            this.wxopen = false;
          } else {
            this.msgError(response.msg);
          }
        });
      }

    },
    smssubmitForm: function() {
      let params = {
        query: this.queryParams,
        type: this.sendType,
        smsMsgTemp: this.smsMsgTemp,
        ids:   this.ids,
      }
      if (this.sendBySelected){
        msgSendBySelected(params).then(response => {
          if (response.code === 200) {
            this.msgSuccess("操作成功");
            this.wxopen = false;
          } else {
            this.msgError(response.msg);
          }
        });
      }else{
        msgSend(params).then(response => {
          if (response.code === 200) {
            this.msgSuccess("操作成功");
            this.smsopen = false;
          } else {
            this.msgError(response.msg);
          }
        });
      }

    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除用户编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delMember(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 微信模板消息按钮操作 */
    handleWxMsg() {
      this.sendBySelected = false;
      this.sendType = 1;
      this.wxopen = true;
      this.wxtitle = "编辑模板内容";
    },
    /** 短信模板消息按钮操作 */
    handleSmsMsg() {
      this.sendBySelected = false;
      this.sendType = 2;
      this.smsopen = true;
      this.smstitle = "短信模板消息";
    },

    /** 微信模板消息按钮操作 */
    handleWxMsgSelected() {
      this.sendBySelected = true;
      this.sendType = 1;
      this.wxopen = true;
      this.wxtitle = "编辑模板内容";
    },
    /** 短信模板消息按钮操作 */
    handleSmsMsgSelected() {
      this.sendBySelected = true;
      this.sendType = 2;
      this.smsopen = true;
      this.smstitle = "短信模板消息";
    },
    enableFormat(row, column) {
      return this.selectDictLabel(this.enableOptions, row.isEnable);
    },
    memPermFormat(row, column) {
      return this.selectDictLabel(this.memPermOptions, row.memPerm);
    },
    isWxsubFormat(row, column) {
      return this.selectDictLabel(this.isWxSubOptions, row.isWxsub);
    },
    handleImport(){
      this.importMemberOpen = true;
    },
    handleUploadSuccess(res, file) {
      this.msgSuccess("导入操作已完成");
      this.getList()
    },
    beforeUpload(file) {
      let extension = file.name.substring(file.name.lastIndexOf('.')+1);
      // 判断文件类型
      let isType = extension == 'xlsx'  || extension == 'xls';
      if(!isType) {
        this.$message.warning('只能上传后缀是.xlsx或者.xls的文件');
      }
      const isLt = file.size / 1024 / 1024 < 4;
      if (!isLt) {
        this.$message.error('上传文件大小不能超过4M!');
      }
      return isType && isLt;
    },
  }
};
</script>
